<?php
//This script uses an HTML Form to add new records to the .txt file.
//Only input required is the url and category, date and counter are automated.
//Saxon Dakin, 7392176

include 'menu.php';

//If loop to check if submit button has been pressed.
if (!isset($_POST['submit']))
{

//Create a friendly UI to easily add to text document
?>
  <html><body>
  <h4>Add a Link to your Favourites</h4>
  <form action="add.php" method="post"> 

  URL: <input name="url" type="text" />
  <!-- Drop down box for catergory-->
  Category: <select name="category"> 
  <option>Search Engines</option>
  <option>Comedy</option>
  <option>Video</option>
  <option>Information</option>
  <option>Other</option>
  </select>
  <br>
  <br>
  <input type="submit" name="submit" />
  </form>
  </body></html>
  <br>
  <br>
  
  
  <?php
  //Read file into an array.
  $filename = "favourites.txt";
  $fd = fopen ($filename, "r");
  $favourites = fread ($fd,filesize ($filename));
  fclose ($fd);
  $splitfavourites = explode("\n", $favourites);
  
  $counter =0;
  
  //Turn into a seperate array named $items to split each line into 1 value per element
  foreach ($splitfavourites as $value)
  {
    $items[$counter] = explode("|", $value);
    $counter++;
  }
  
  //Turn into an HTML table
  $favourites = "<table border='1'><tr><th>URL</th><th>Category</th><th>Date</th><th>Counter</th></tr>";
  $sizeof_arr = sizeof($items);
  $counter = 0;
  
  //For loop to seperate each $items value into it's correct colum using the keys
  for ($i=0; $i<$sizeof_arr; $i++)
  {
    $favourites .= "<tr><td>";
    $favourites .=  $items[$i][0];
    $favourites .=  "</td><td>" . $items[$i][1];
    $favourites .=  "</td><td>" . $items[$i][2];
    $favourites .=  "</td><td>" . $items[$i][3];
    $favourites .=  "</td></tr>";
  }
  
  $favourites .= "</tr></table>";
  
  //Display table
  echo $favourites;    
}
else
{
  //After submit the inputed data is posted to these variables
  $url = $_POST['url'];
  $category = $_POST['category'];
  $date = date("d/m/Y") ;
  $counter = 0;
  
  //use a substr to check if http:// was added to the link, if not it adds it.
  $var  = substr($url,0,7);
  if($var == "http://")
  {
  $you = "rock";
  }
  else
  {
  $url = "http://" . $url;
  }

  //writes to text file
  $fh = fopen("favourites.txt","a");
  $data = "\r\n" . $url . "|" . $category . "|" . $date . "|" . $counter;
  
  fwrite($fh, $data);
  fclose($fh);

  echo "You added ". $url . " to category " . $category . ", on " . $date . "<br />";
  ?>
  
  <br>
  <br>
  <a href="add.php">Click here to Return</a>
  
  <?php
}
?>